import { ActionContext } from 'vuex'
import * as $api from '@/api/dictionary'
import { IStore } from '../types'

export type IDictionaryState = {
  list: DictionaryData
}
interface DictionaryData {
  label: string
  children: DictionaryList
}
interface DictionaryList {
  label: string
  value: string | number
}

const state = {
  list: {}
}
const mutations = {
  // 设置全局存储的字典map
  SET_DICTIONARY: (state: any, data: DictionaryData) => {
    state.list = {
      ...state.list,
      ...data
    }
  }
}
const actions = {
  // 获取字典表列表数据
  getDictionary({ commit }: ActionContext<IDictionaryState, IStore>, params: $api.DictionaryParams) {
    return new Promise((resolve, reject) => {
      $api
        .getDictionary(params)
        .then((res) => {
          const { data } = res
          const dict = {}
          data.forEach((item: any) => {
            Object.assign(dict, {
              [item.label]: item.children.map((val: DictionaryList) => {
                return {
                  label: val.label,
                  value: /^(\-|\+)?\d+$/.test(<string>val.value) ? +val.value : val.value
                }
              })
            })
          })
          commit('SET_DICTIONARY', dict)
          resolve(dict)
        })
        .catch(() => {
          reject()
        })
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
